//index.js
//获取应用实例
const app = getApp()
var wsUrl = "wss://" + "www.bjhylfkj.com" + "/websocket";
var lockReconnect = false; //避免重复连接
var ws;
var tt;
Page({
  data: {
    socketStatus: 'closed',
    motto: '首页',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    courseList: [],
    topicArray: [],
    serverUrl: '',
    code: '',
    openid: '',
    session_key: '',
    encryptedData: '',
    iv: '',
    credit: 0,
    points: 0,
    tmpl: ['https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2763523135,381182796&fm=26&gp=0.jpg',  'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1587726846541&di=c7c5eb03e02fff3a03a5a8e1a460a9df&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201510%2F20%2F20151020194029_wcySK.jpeg'],
    swipelist: ['https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2763523135,381182796&fm=26&gp=0.jpg', '6Go4b3zlwiB58u8QRu8l3xEDSYH7EKkMistrsnlViVY', 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1587726846541&di=c7c5eb03e02fff3a03a5a8e1a460a9df&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201510%2F20%2F20151020194029_wcySK.jpeg'],
    current: 1,
    tiptxt: '加载更多',
    //该标志用于控制某些显示
    shenhe: true,
    adusec: true

  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

  onLoad: function() {

    var sdf = app.globalData.userInfo;
    let _this = this;
     
    if (sdf == null) {
      this.getUserObject(sdf);
    }

    if (app.globalData.userInfo) {
      console.log("用户已经存在")
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
        encryptedData: app.data.encryptedData,
        iv: app.data.iv
      })
    } else if (this.data.canIUse) {

      app.userInfoReadyCallback = res => {
        console.log("授权登录成功")
        _this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
          encryptedData: res.encryptedData,
          iv: res.iv
        })
      }
    } else {
      console.log("huoq yong hu")
    }

    //从后台发起请求，来提交逻辑
    app.paiRequest("app/course/tcourses/changeList", {
      
    }).then(function (res) {
      var list = res.data.data;
      app.globalData.audFlag=res.data.audFlag
      app.globalData.audSecFlag = res.data.audscFlag
      _this.setData({
        swipelist: list,
        //shenhe: res.data.audFlag,
        shenhe: res.data.audFlag,
        adusec: res.data.audSecFlag
       
      })
    })


    


    this.gethomedata()
  },
  tomsg() {
    wx.showToast({
      title:"敬请期待！",
      icon: 'none'
    })
  },
  //加载数据
  gethomedata() {
    let _this = this
    app.paiRequest("/app/course/tcourses/homeData", {
      item: this.data.current,
      pageNo: 1,
      pageSize: 10
    }).then(function(res) {
      var list = res.data;
      var serverUrl = app.data.server;
      let courseList = _this.data.courseList
      if (courseList.length == 0 && list.coursesArray == 0) {
        _this.setData({
          tiptxt: '暂无数据'
        })
        return false
      }
      if (courseList.length != 0 && list.coursesArray == 0) {
        _this.setData({
          tiptxt: '已加载全部'
        })
        return false
      }
      courseList = courseList.concat(list.coursesArray)
      let topicArray = _this.data.topicArray
      topicArray = topicArray.concat(list.topicArray)
      _this.setData({
        courseList: courseList,
        topicArray: topicArray,
        serverUrl: serverUrl
      })
      //
      _this.data.current++
    })
  },
  /**
   * url: 'ws://' + "www.bjhylfkj.com" + "/websocket",
   */
  openSocket(userId) {
    var _this = this;
    wx.onSocketOpen(() => {

      this.data.socketStatus = 'connected';
      _this.heartStart(userId);
    });
    wx.onSocketClose(() => {
      _this.openSocket(userId);
    });
    wx.onSocketError(error => {
      console.error('socket error:', error);
    });
    wx.onSocketMessage(message => {
      message = message.data.replace(" ", "");
      var jsd = JSON.parse(message);
      console.log(jsd)
      var receUser = jsd.userId;
      var userInfo = app.globalData.userInfo;
      console.log(userInfo);
      if (userInfo != null) {
        var curnUserId = userInfo.id;
        if (receUser === curnUserId) {
          var num = jsd.num;
          var relogin = app.globalData.relogin;
          if (relogin != true) {
            if (userInfo.sessionKey != jsd.sessionKey && jsd.sessionKey != undefined) {
              app.globalData.relogin = true;
              app.globalData.userInfo = null;
              wx.navigateTo({
                url: '/pages/login/index',
              })
            }
          }
          if (num != undefined && num > 0) {
            var systeminfo = userInfo.systeminfo;
            userInfo.systeminfo = num;
            this.setData({
              userInfo: userInfo
            })
            if (num > systeminfo) {
              this.playMp();
            }
          }

        }
      }
    })
    wx.connectSocket({
      url: wsUrl,
    })
  },
  playMp() {
    const innerAudioContext = wx.createInnerAudioContext();
    innerAudioContext.autoplay = true;
    innerAudioContext.src = "/images/8855.mp3";
    innerAudioContext.onPlay(() => {

    });
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
    })
  },
  closeSocket() {
    if (this.data.socketStatus === 'connected') {
      wx.closeSocket({
        success: () => {
          this.globalData.socketStatus = 'closed'
        }
      })
    }
  },
  sendMessage(message) {
    if (this.data.socketStatus === 'connected') {
      wx.sendSocketMessage({
        data: message
      })
    }
  },
  heartStart: function(userId) {
    var _this = this;
    var sf = JSON.stringify({
      userId: userId
    });
    setInterval(function() {
      if (_this.data.socketStatus === 'connected') {
        wx.sendSocketMessage({
          data: sf
        })
      }
    }, 20000)
  },

  getUserObject: function(info) {
    let _this = this;
    wx.login({
      success: res => {
        var code = res.code;

        var sumit = {
          appid: 'wxd598d704f54aa600',
          secret: '09ff4e7f657eda6eecb4041d77fc58af',
          js_code: res.code
        };
        app.paiRequest("/app/user/openiduser", sumit).then(function(res) {
          var data = res.data;
          getApp().globalData.userInfo = data;
          getApp().data.openid = data.wxOpenid;
          _this.setData({
            userInfo: data
          })
          var systeminfo = data.systeminfo;
          if (systeminfo > 0) {
            _this.playMp();
          }
          if (_this.data.socketStatus === 'closed') {
            _this.openSocket(data.id);
          }
        })

      }
    })
  },
  showMessage: function(message) {
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 3000,
      mask: true
    })
  },


  onShow: function() {
    this.setData({
      userInfo: app.globalData.userInfo
    })

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var _this = this;
    wx.showNavigationBarLoading();
    var userInfo = app.globalData.userInfo;
    if (_this.data.socketStatus === 'closed') {
      _this.openSocket(userInfo.id);
    }
    app.paiRequest("/app/course/tcourses/homeData", {
      item: 1
    }).then(function(res) {
      console.log(res);
      var list = res.data;
      var relogin = app.globalData.relogin;
      if (list.sessionKey != undefined && userInfo.sessionKey != list.sessionKey) {
        app.globalData.relogin = true;
        wx.navigateTo({
          url: '/pages/login/index',
        })
      }

      var serverUrl = app.data.server;
      _this.setData({
        courseList: list.coursesArray,
        topicArray: list.topicArray,
        serverUrl: serverUrl,
        userInfo: userInfo
      })
    })

    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  /**
   * 进入
   */
  courseList: function(event) {
    var code = event.currentTarget.dataset.code;
    wx.navigateTo({
      url: '../' + code,
    })
  },
  navPage: function(e) {
    var src = e.currentTarget.dataset.src;
    var score = e.currentTarget.dataset.score;
    wx.navigateTo({
      url: src + "?score=" + score,
    })
  },
  videolive: function(event) {
    wx.navigateTo({
      url: '../videolive/index',
    })
  },
  selectTarBar: function(event) {
    let src = event.currentTarget.dataset.src;
    wx.switchTab({
      url: '../' + src,
    })
  },
  selectDish: function(event) {
    let id = event.currentTarget.dataset.dish;
    let src = event.currentTarget.dataset.src;
    console.log(src);
    wx.navigateTo({
      url: '../' + src + '?id=' + id,
    })
  },
  selectDish2: function(event) {
    let id = event.currentTarget.dataset.dish;
    let src = event.currentTarget.dataset.src;
    wx.navigateTo({
      url: src + '?id=' + id,
    })
  },
  messageList: function() {
    var userInfo = this.data.userInfo;
    wx.navigateTo({
      url: '../systeminfo/index?userId=' + userInfo.id,
    })
  }
})